#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
****************************************************
Project:python
Filename: middleware.py
Author:银河
Create: 2025/3/25 下午1:33 
Notes:
***************************************************
'''

# middleware.py
import logging

logger = logging.getLogger(__name__)


class LogIPMiddleware:
    # def __init__(self, get_response=None):
        # super().__init__(get_response)  # 调用父类的 __init__ 方法
        # self.logger = logging.getLogger('utils.middleware')
    def __init__(self, get_response=None):
        self.get_response = get_response

    def __call__(self, request):
        # 获取客户端 IP 地址
        ip_address = self.get_client_ip(request)
        # print(request)
        # print(request.META)
        logger.info(f"Request received from IP: {request}-{ip_address}")

        response = self.get_response(request)
        return response

    def get_client_ip(self, request):
        # 优先从 X-Forwarded-For 头获取 IP 地址
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            # 如果有多个代理，取第一个非空值
            ip = x_forwarded_for.split(',')[0].strip()
        else:
            # 否则直接从 REMOTE_ADDR 获取
            ip = request.META.get('REMOTE_ADDR')
        return ip